#!/bin/bash

usage(){
    echo "Usage: $(basename $0) OPTIONS"
    echo "OPTIONS:"
    echo -e "\t-l                local proxy http://localhost:8118"
    echo -e "\t-p [URL of proxy] URL as proxy"
    echo -e "\t-h                Print This Message"
    exit 1
}
if [[ $(uname) != "Darwin" ]];then
    echo "Only run on macOS"
    exit 1
fi

user=${SUDO_USER:-$(whoami)}
proxy=
while getopts ":lp:h" opt;do
    case $opt in
        h)
            usage
            ;;
        l)
            proxy="socks5://localhost:1080"
            ;;
        p)
            proxy=$OPTARG
            ;;
        :)
            echo "option:\"$OPTARG\" need argument!!"
            exit 1
            ;;
        \?)
            echo "Option: \"$OPTARG\" not support!!"
            exit 1
            ;;
    esac
done
SCRIPTDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPTDIR"

if (($EUID!=0));then
    #非root用户的时候,需要检测是否有sudo命令,如果有sudo命令则还要检测当前用户是否可以使用sudo命令
    #因为下面有的指令需要root权限
    if command -v sudo >/dev/null 2>&1;then
        sudo true || { echo "Error: Current user cannot use command 'sudo' !";exit 1; }
    else
        echo "Error: Current user is not root,and can not find sudo cmd!"
        exit 1
    fi
fi

if [[ -n "$proxy" ]];then
    echo "using proxy: $proxy"
    shopt -s expand_aliases

    #set brew proxy
    alias brew="ALL_PROXY=$proxy brew"
    #set curl proxy
    #curl -x or curl --proxy or http_proxy environment variable
    #support http or socks5 proxy
    alias curl="curl -x $proxy"
    #set git proxy
    git config --global http.proxy "$proxy"

    #set wget proxy
    export http_proxy="$proxy"
    export https_proxy="$proxy"
    export ftp_proxy="$proxy"

    export HTTP_PROXY="$proxy"
    export HTTPS_PROXY="$proxy"
    export FTP_PROXY="$proxy"
fi
if [[ -n "$proxy" ]];then
    /bin/bash dev/dev-mac -p $proxy
else
    /bin/bash dev/dev-mac
fi

echo "Config git..."
/bin/bash git/setGit

echo "Install zsh and oh-my-zsh..."
/bin/bash shell/10-zsh-installer.sh
/bin/bash shell/20-set-zsh-theme.sh
/bin/bash shell/30-config-shell.sh install

echo "Install supervim for nvim..."
if [[ -n "$proxy" ]];then
    /bin/bash supervim/install.sh -f -p $proxy nvim
else
    /bin/bash supervim/install.sh -f nvim
fi

echo "Install supervim for vim..."
if [[ -n "$proxy" ]];then
    /bin/bash supervim/install.sh -f -p $proxy  vim
else
    /bin/bash supervim/install.sh -f vim
fi
